package com.xiechuang.util.copy;

import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;

import java.util.List;

/**
 * @Description orika Java Bean转换组件
 * @Author xiechuang
 * @Date 2022/1/6
 */
public class OrikaMapperUtil {

    /**
     * 获取默认字段工厂
     **/
    private static final MapperFactory MAPPER_FACTORY;
    /**
     * 默认字段实例
     **/
    private static final MapperFacade MAPPER_FACADE;

    static {
        // mapNulls 源对象中的null不会拷贝到目标对象
        MAPPER_FACTORY = new DefaultMapperFactory.Builder().mapNulls(false).build();
        MAPPER_FACADE = MAPPER_FACTORY.getMapperFacade();
    }

    /**
     * source --> toClass 属性名字相同 进行赋值
     *
     * @param source  源对象
     * @param toClass 目标对象
     * @return 映射类对象
     */
    public static <S, D> D convert(S source, Class<D> toClass) {
        return MAPPER_FACADE.map(source, toClass);
    }

    /**
     * source --> toClass 属性名字相同 进行赋值
     *
     * @param source 源对象
     * @param target 目标对象
     */
    public static <S, D> void convert(S source, D target) {
        MAPPER_FACADE.map(source, target);
    }

    /**
     * sources --> targetClass 属性名字相同 进行赋值
     *
     * @param sources     源对象列表
     * @param targetClass 目标对象字节码
     * @return 目标对象列表
     */
    public static <S, D> List<D> convertList(Iterable<S> sources, Class<D> targetClass) {
        return MAPPER_FACADE.mapAsList(sources, targetClass);
    }

}
